package com.cz.ssyx.acl.utils;

import com.cz.ssyx.model.acl.Permission;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @descriptions:
 * @author: Joker.
 * @date: 2024/4/16 21:05
 * @version: 1.0
 */

public class PermissionHelper {

    //转换菜单数据格式
    public static List<Permission> buildPermission(List<Permission> allPermissions){

        //创建一个最终格式的集合
        ArrayList<Permission> trees = new ArrayList<>();

        //遍历全部菜单
        for (Permission permission : allPermissions) {
            if (permission.getPid() == 0) {
                //如果Pid为0，是第一层菜单，设置等级为1
                permission.setLevel(1);

                //递归遍历下一级菜单
                trees.add(findChildren(permission, allPermissions));
            }
        }
        return trees;
    }

    private static Permission findChildren(Permission permission, List<Permission> allList) {
        permission.setChildren(new ArrayList<>());
        //遍历allList中所有菜单数据
        //判断当前菜单permission的id 与 所有菜单数据的Pid是否相等
        for (Permission cPermission : allList) {
            if (permission.getId().longValue() == cPermission.getPid().longValue()) {
                //设置下一层的层数
                int level = permission.getLevel() + 1;
                cPermission.setLevel(level);

                if (permission.getChildren() == null){
                    permission.setChildren(new ArrayList<>());
                }

                //封装下一层数据
                permission.getChildren().add(findChildren(cPermission, allList));
            }
        }


        return permission;
    }
}
